<script setup lang="ts">
import {ref} from 'vue'
import {useAnalysetStore} from "@/store";
import AnalyesAPI from "@/api/system/analyes";

const analyseStatusPage = useAnalysetStore()
const form = ref({})
const qcForm = ref({})
const analyseTableList = ref([])
const personnelList = ref([])
const sampleSnList = ref([])
const paramsString = ref('')
const assignedDialogVisible = ref(false)
const id = ref(0)
const userForm = ref({
  analysis_uid: '',
  notes: '',
  paramsString: '',
  analysis_names: '',
})
const activeName = ref('first')
onMounted(() => {
  // 分析单详情
  getStatusPageDetail()
//   质控单详情
  getStatusQcPageDetail()
  //   获取分析人
  getPersonnelList()
//   获取样品编号
  handleSwitchdrawer()
})
const handleClick = (tab) => {
  activeName.value = tab.props.name
}

// 获取分析单详情
function getStatusPageDetail() {
  AnalyesAPI.getAssignDetail({task_id: analyseStatusPage.analyseStatusForm.status, test_category: analyseStatusPage.analyseStatusForm.test_category}).then(data => {
    console.log('分析单详情', data)
    form.value = {...data.order, ...data.task_info}
    analyseTableList.value = data.test_parms
  })
}

// 获取分析单详情
function getStatusQcPageDetail() {
  AnalyesAPI.getQcDetailsPage({qc_id: analyseStatusPage.analyseStatusForm.qcStatus, test_category: analyseStatusPage.analyseStatusForm.test_category}).then(data => {
    console.log('质控单详情', data)
    qcForm.value = data
  })
}

// 获取分析人
function getPersonnelList() {
  AnalyesAPI.getPersonnel({group_id: 3}).then(data => {
    console.log('分析人', data)
    personnelList.value = data
  })
}


// 打开弹框
function handleOpenDialog(row) {
  id.value = row.id
  userForm.value.paramsString = `${row.sample_category}（${row.test_parms}）`;
  assignedDialogVisible.value = true
}

// 确认重新分派
function handleAddApportion() {
  userForm.value.analysis_names = personnelList.value
      .filter(person => userForm.value.analysis_uid.includes(person.id))
      .map(item => item.username)
      .join('，'); // 多人用逗号分隔
  let userId = userForm.value.analysis_uid.map(item => item).join(',')
  console.log(userForm.value)
  const formData = new FormData();
  formData.append('analysis_uids', userId);
  formData.append('analysis_names', userForm.value.analysis_names);
  formData.append('notes', userForm.value.notes);
  formData.append('id', id.value);
  formData.append('task_id', analyseStatusPage.analyseStatusForm.status);
  AnalyesAPI.oncemoreAssign(formData).then(data => {
    if (!data) {
      ElMessage.success('分派成功！')
      assignedDialogVisible.value = false
      // 调用列表
      getStatusPageDetail()
      userForm.value = {}
    } else {
      ElMessage.error('操作失败！')
      assignedDialogVisible.value = false
    }
  })
}

function handleClose() {
  assignedDialogVisible.value = false
}

// 获取样品编号
const handleSwitchdrawer = () => {
  let json = {
    task_id: analyseStatusPage.analyseStatusForm.status,
    test_category: analyseStatusPage.analyseStatusForm.test_category,
  }
  AnalyesAPI.getSamplesn(json).then(res => {
    console.log('样品编号', res)
    if (analyseStatusPage.analyseStatusForm.test_category === '来样检测') {
      sampleSnList.value = mergeDataByTestParms(res)
    } else {
      sampleSnList.value = res
    }
  })
}

const mergeDataByTestParms = (data) => {
  return data.reduce((acc, item) => {
    // 查找是否已经有相同的 test_parms 和 sample_category
    const existing = acc.find(entry => entry.test_parms === item.test_parms && entry.sample_category === item.sample_category);

    if (existing) {
      // 如果已经存在相同的 test_parms 和 sample_category，直接添加到 list 中
      existing.list.push({
        "sample_sn": item.sample_sn,
        "sampling_date": item.sampling_date
      });
    } else {
      // 如果不存在相同的 test_parms 和 sample_category，创建一个新条目
      acc.push({
        "test_parms": item.test_parms,
        "sample_category": item.sample_category,
        "list": [{
          "sample_sn": item.sample_sn,
          "sampling_date": item.sampling_date
        }]
      });
    }

    return acc;
  }, []);
}
</script>

<template>
  <div class="card">
    <el-card class="box-card">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="分析任务单详情" name="first">
          <el-row>
            <el-col :span="6" class="syc-flex syc-flex-align-center ">
              任务名称：{{ form.task_name }}
            </el-col>
            <el-col :span="6" class="syc-flex syc-flex-align-center ">
              任务单号：{{ form.task_number }}
            </el-col>
            <el-col :span="6" class="syc-flex syc-flex-align-center ">
              关联委托单号：{{ form.order_number }}
            </el-col>
            <el-col :span="6" class="syc-flex syc-flex-align-center ">
              项目名称：{{ form.project_name }}
            </el-col>
            <el-col :span="6" class="syc-flex syc-flex-align-center ">
              检测周期：{{ form.test_period }}
            </el-col>
            <el-col :span="6" class="syc-flex syc-flex-align-center ">
              采样地点：{{ form.task_address }}
            </el-col>
            <el-col :span="6" class="syc-flex syc-flex-align-center ">
              分派人：{{ form.issueder }}
            </el-col>
            <el-col :span="6" class="syc-flex syc-flex-align-center ">
              分派时间：{{ form.issuedtime }}
            </el-col>
            <el-col :span="6" class="syc-flex syc-flex-align-center ">
              状态：{{
                form.analysis_status == '1' ? '待分派' : form.status == '2' ? '已分派' : form.status == '3' ? '草稿' : ''
              }}
            </el-col>
          </el-row>
        </el-tab-pane>
        <!--        <el-tab-pane label="质控单详情" name="second">-->
        <!--          <el-row>-->
        <!--            <el-col :span="6" class="syc-flex syc-flex-align-center ">-->
        <!--              质控单号：{{ qcForm?.qc_info?.qc_number }}-->
        <!--            </el-col>-->
        <!--            <el-col :span="6" class="syc-flex syc-flex-align-center ">-->
        <!--              任务名称：{{ qcForm?.order_info?.task_name }}-->
        <!--            </el-col>-->
        <!--            <el-col :span="6" class="syc-flex syc-flex-align-center ">-->
        <!--              任务单号：{{ qcForm?.order_info?.task_number }}-->
        <!--            </el-col>-->
        <!--            <el-col :span="6" class="syc-flex syc-flex-align-center ">-->
        <!--              关联委托单号：{{ qcForm?.task_info?.task_number }}-->
        <!--            </el-col>-->
        <!--            <el-col :span="6" class="syc-flex syc-flex-align-center ">-->
        <!--              项目名称：{{ qcForm?.order_info?.project_name }}-->
        <!--            </el-col>-->
        <!--            <el-col :span="6" class="syc-flex syc-flex-align-center ">-->
        <!--              检测周期：{{ qcForm?.task_info?.test_period }}-->
        <!--            </el-col>-->
        <!--            <el-col :span="6" class="syc-flex syc-flex-align-center ">-->
        <!--              采样地点：{{ qcForm?.order_info?.sampling_address }}-->
        <!--            </el-col>-->
        <!--            <el-col :span="6" class="syc-flex syc-flex-align-center ">-->
        <!--              状态：{{-->
        <!--                qcForm?.order_info?.status == '1' ? '待下发' : qcForm?.order_info?.status == '2' ? '已下发' : qcForm?.order_info?.status == '3' ? '已取消' : ''-->
        <!--              }}-->
        <!--            </el-col>-->
        <!--          </el-row>-->
        <!--        </el-tab-pane>-->
        <el-tab-pane label="样品编号详情" name="third">
          <el-card class="box-card" style="margin-top: 30px">
            <div class="card-button" style="margin-bottom: 30px">
              样品编号
            </div>
            <el-table style="width: 100%" border :data="sampleSnList">
              <el-table-column label="序号" align="center">
                <template #default="scope">{{ scope.$index + 1 }}</template>
              </el-table-column>
              <el-table-column prop="sample_category" label="样品类别" align="center">
              </el-table-column>
              <el-table-column prop="test_parms" label="检测参数" align="center">
              </el-table-column>
              <el-table-column prop="" label="样品编号" align="center" width="800">
                <template #default="scope">
                  <div v-if="scope.row.sample_sn === undefined">
                    <div v-for="(item,index) in scope.row.list" :key="index">
                      <div style="text-align: left;margin-left: 20px">{{ item.sample_sn }} {{ item.sampling_date }} 、
                      </div>
                    </div>
                  </div>
                  <div v-else style="text-align: left;margin-left: 20px">
                    {{ scope.row.sample_sn }} {{ scope.row.sampling_date }}
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <template v-if="activeName === 'first'">
      <!--    表格内容-->
      <el-card class="box-card" style="margin-top: 30px">
        <div class="card-button" style="margin-bottom: 30px">
          检测参数
        </div>
        <el-table style="width: 100%" border :data="analyseTableList">
          <el-table-column prop="name" label="操作" align="center">
            <template #default="scope">
              <el-dropdown>
                <el-button type="primary" size="small">
                  操作
                  <el-icon class="el-icon--right">
                    <arrow-down/>
                  </el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleOpenDialog(scope.row)">重新分派</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="序号" align="center">
            <template #default="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column prop="sample_category" label="样品类别" align="center">
          </el-table-column>
          <el-table-column prop="test_parms" label="检测参数" align="center">
            <template #default="scope">
              <div>
                <span v-show="scope.row.test_parms_type === 1">*</span>
                {{ scope.row.test_parms }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="test_method" label="检测依据" align="center">
            <template #default="scope">
              <span>{{ scope.row.test_method === null ? scope.row.test_method_number : scope.row.test_method }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="analysis_names" label="分析人" align="center">
          </el-table-column>
          <el-table-column prop="check_name" label="校核人" align="center">
          </el-table-column>
          <el-table-column prop="notes" label="备注" align="center">
          </el-table-column>
        </el-table>
      </el-card>
      <!--      <div class="pagination">-->
      <!--        <el-pagination-->
      <!--            background-->
      <!--            layout="prev, pager, next"-->
      <!--            :total="20">-->
      <!--        </el-pagination>-->
      <!--      </div>-->

      <el-dialog title="分派" v-model="assignedDialogVisible" width="30%" center :before-close="handleClose">
        <el-form ref="form" :model="userForm" label-width="90px">
          <el-form-item label="检测参数：">
            {{ userForm.paramsString }}
          </el-form-item>
          <el-form-item label="分析人：">
            <el-select v-model="userForm.analysis_uid" multiple placeholder="请选择">
              <el-option
                  v-for="(label, value) in personnelList"
                  :key="value"
                  :label="label.username"
                  :value="label.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注：">
            <el-input v-model="userForm.notes" placeholder="单行输入"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" style="display: flex;justify-content: center">
          <el-button @click="handleClose" style="width: 50%">取 消</el-button>
          <el-button type="primary" style="width: 50%" @click="handleAddApportion">确 定</el-button>
      </span>
      </el-dialog>
    </template>
    <template v-if="activeName === 'second'">
      <!--    表格内容-->
      <el-card class="box-card" style="margin-top: 30px">
        <div class="card-button" style="margin-bottom: 30px">
          分析质控
        </div>
        <el-table style="width: 100%" border :data="qcForm.qcanalysismethod_info">
          <el-table-column label="序号" align="center">
            <template #default="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column prop="sample_category" label="样品类别" align="center">
          </el-table-column>
          <el-table-column prop="analysis_params" label="检测参数" align="center">
          </el-table-column>
          <el-table-column prop="analysis_qc_method" label="质控措施" align="center">
            <!--            <template #default="scope">-->
            <!--              {{ scope.row.sampling_qc_method_a }}-->
            <!--              &lt;!&ndash; {{ scope.row.sampling_qc_method_b }} &ndash;&gt;-->
            <!--            </template>-->
          </el-table-column>
          <el-table-column prop="analysis_qc_note" label="备注" align="center">
          </el-table-column>
        </el-table>
      </el-card>
      <!--      <div class="pagination">-->
      <!--        <el-pagination-->
      <!--            background-->
      <!--            layout="prev, pager, next"-->
      <!--            :total="20">-->
      <!--        </el-pagination>-->
      <!--      </div>-->
    </template>

  </div>
</template>

<style scoped lang="scss">
.card {
  padding: 20px 25px;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

.syc-flex {
  display: flex;
}

.syc-flex-align-center {
  margin: 10px 0;
  align-items: center;
}

.syc-flex-justify-center {
  justify-content: center;
}

</style>
